package com.zcz;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class SomeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            if (ServletFileUpload.isMultipartContent(request)) {
                ServletFileUpload upload = new ServletFileUpload(factory);

                List<FileItem> fileItems = upload.parseRequest(request);

                for (FileItem item : fileItems) {
                    for (FileItem fileItem : fileItems) {
//你不好
                        if(fileItem.isFormField()){
                            String name = fileItem.getFieldName();
                            String value = fileItem.getString("UTF-8");
                            System.out.println(name+" "+value);
                        }else{
                            String name = fileItem.getName();//文件名称  a.txt
                            InputStream is = fileItem.getInputStream();//文件内容
                            //获取一个文件输出的磁盘路径
                            String path = getServletContext().getRealPath("/update");
                            OutputStream os = new FileOutputStream(path+"/"+name);
//你好
                            int i = 0;
                            byte[] bys = new byte[1024];

                            while((i=is.read())!=-1){
                                os.write(bys, 0, i);
                            }
                            os.close();
                            is.close();
                        }
                    }
                }

            } else {
                System.out.println("呵呵呵");
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
